package com.itheima.activiti.service.activiti.impl;

import com.itheima.activiti.auth.JwtContextUtils;
import com.itheima.activiti.dto.activiti.ProcessDataDTO;
import com.itheima.activiti.service.activiti.ProcessService;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ProcessServiceImpl implements ProcessService {

    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private HistoryService historyService;
    @Autowired
    private TaskService taskService;

    @Override
    public ProcessDataDTO processData(String businessId) {
        ProcessDataDTO processDataDTO = new ProcessDataDTO();
        try {
            String processInstanceId;
            // 根据业务id，查询流程实例
            ProcessInstance processInstance = runtimeService.createProcessInstanceQuery()
                    .processInstanceBusinessKey(businessId)
                    .singleResult();
            Task task = null;
            if (processInstance == null) {
                // 根据流程实例，查询历史流程实例
                HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery()
                        .processInstanceBusinessKey(businessId)
                        .singleResult();
                processInstanceId = historicProcessInstance.getId();
                processDataDTO.setState("已完成");
            } else {
                processInstanceId = processInstance.getId();
                processDataDTO.setState("进行中");
                // 进行中的业务查询当前执行的任务
                task = taskService.createTaskQuery().processInstanceId(processInstanceId).list().get(0);
            }
            // 设置流程实例id
            processDataDTO.setProcessInstanceId(processInstanceId);

            //查询历史流程任务
            List<HistoricTaskInstance> list = historyService.createHistoricTaskInstanceQuery()
                    .processInstanceId(processInstanceId)
                    .orderByHistoricTaskInstanceStartTime().desc()
                    .list();

            // 设置任务id
            processDataDTO.setTaskId(list.get(0).getId());
            // 设置任务状态
            processDataDTO.setStatus(list.get(0).getName());
            // 设置撤回按钮是否显示  // 处理历史中最后一个节点 和当前节点不一致时 可以撤回
            processDataDTO.setRecallStatus((task != null && !list.get(list.size() - 1).getTaskDefinitionKey().equals(task.getTaskDefinitionKey())) ? 1 : 0);
            // 设置提交按钮是否显示  // 当前任务处理人是当前登录用户、并且历史记录中存在当前的节点+处理人(证明之前处理过)
            processDataDTO.setCommitStatus((task != null && task.getAssignee().equals(JwtContextUtils.getUser().getId().toString()) && list.stream().map(item -> item.getTaskDefinitionKey() + item.getAssignee()).collect(Collectors.toSet()).contains(task.getTaskDefinitionKey() + task.getAssignee())) ? 1 : 0);
        } catch (Exception e) {
            log.warn("流程信息查询失败", e);
        }
        return processDataDTO;
    }
}
